package th.go.drr.gps.web.security;

import java.util.Collection;
import java.util.HashSet;

import org.apache.log4j.Logger;
import org.springframework.security.core.GrantedAuthority;

import th.go.drr.gps.domain.Authority;
import th.go.drr.gps.domain.Usr;
import th.go.drr.gps.repository.h.AuthenticationHandler;
import th.go.drr.gps.web.security.h.UserDetails;

public class UserData implements UserDetails {
	
	private static final long serialVersionUID = 5816778598838214628L;
	private static Logger logger = Logger.getLogger(UserData.class);

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {		
		return this.authorities;
	}

	@Override
	public String getPassword() {	
		return this.passwd;
	}

	@Override
	public String getUsername() {	
		return this.username;
	}

	@Override
	public boolean isAccountNonExpired() {	
//		return !this.accountExpired;
		return true;		
	}

	@Override
	public boolean isAccountNonLocked() {
//		return !this.accountLocked;
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
//		return !this.credentialsExpired;
		return true;		
	}

	@Override
	public boolean isEnabled() {		
//		return this.enable;
		return true;
	}
	private String username;
	private String passwd;
	private boolean accountExpired = false;
	private boolean accountLocked = false;
	private boolean credentialsExpired = false;
	private boolean enable = false;
	private Collection<GrantedAuthorityImp> authorities;	
	public void load(AuthenticationHandler authentication,String uname){
		Usr  u = authentication.findByUserName(uname);
		if(u== null)
			return ;
		this.username = u.getUsername();
		this.passwd = u.getPasswd();
		this.authorities = new HashSet<GrantedAuthorityImp>();
		try{
		for(Authority a :u.getAuthorities()){
			authorities.add(new GrantedAuthorityImp(a.getAuthority()));
		}
		}catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
//		try{
//		for(Authority a :u.getAuthorities())
//			this.authorities.add(new GrantedAuthorityImp(a.getAuthority()));
//		}catch (Exception e) {
//			logger.error(e.getMessage(), e);
//		}		
	}
}
